package com.tl.commonlibrary.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.LinearLayout;

import com.tl.commonlibrary.R;

/**
 * Created by jiangzhongshan on 18/2/3.
 */

public class ChoiceContainerLayout extends LinearLayout implements Checkable {
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};

    private boolean mChecked;
    private Checkable checkBox;
    private boolean checkable;

    public ChoiceContainerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Checkable getCheckBox() {
        return checkBox;
    }

    public void setCheckBox(Checkable checkBox) {
        this.checkBox = checkBox;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        this.checkBox = findViewById(R.id.check_box);
    }

    @Override
    public void setChecked(boolean b) {
        if (checkBox != null) {
            checkBox.setChecked(b);
        }
    }

    @Override
    public boolean isChecked() {
        if (checkBox != null) {
            return checkBox.isChecked();
        }
        return false;
    }

    @Override
    public void toggle() {
        if (checkable && checkBox != null) {
            setChecked(!checkBox.isChecked());
        }
    }

    public void setCheckable(boolean checkable) {
        this.checkable = checkable;
    }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {

        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);

        if (isChecked()) mergeDrawableStates(drawableState, CHECKED_STATE_SET);

        return drawableState;
    }
}
